import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/checkin/checkinmodel.dart';
import 'package:opene/ui/checkin/checkinpendingpage.dart';
import 'package:opene/ui/checkin/checkinreceivedpage.dart';
import 'package:opene/ui/lpnphoto/lpnphotodialogscreen.dart';
import 'package:opene/ui/lpnphoto/lpnphotolpnscreen.dart';
import 'package:opene/ui/lpnphoto/lpnphotomodel.dart';
import 'package:opene/ui/tally/tallymodel.dart';
import 'package:toast/toast.dart';

import 'lpnphotosubmitpage.dart';

class LpnPhotoScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return LpnPhotoScreenPage();
  }
}

class LpnPhotoScreenPage extends StatefulWidget {
  @override
  _LpnPhotoPageState createState() => _LpnPhotoPageState();
}

class _LpnPhotoPageState extends BaseState<LpnPhotoScreen> {
  List<Tally> data = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "LPNPhoto:Container";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setLayoutBottomContentGone();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        getContainerNoList();
      });
    });
  }

  void didPopNext() {
    setState(() {
      // 这里刷新页面状态
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 0, top: 10, right: 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(left: 15, top: 0, right: 15, bottom: 0),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 35),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (Utils.isEmpty(text)) {
                    return;
                  }
                  getLpnPhotoInfo(text);
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    padding: EdgeInsets.all(2.0),
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 28,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        setState(() {
                          textEditingController.text = text;
                        });
                        print(text); //拿到扫描结果
                        getLpnPhotoInfo(text);
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "scan inbound lpn barcode",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15,top: 5),
            child: Text(
              "Pending Containers",
              style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 0),
            width: double.infinity,
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 15, right: 10),
              child: setListView(),
            ),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        Tally tally = data[index];
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                  flex: 2, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      lpnPhotoCheckContainer(tally);
                    },
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          Utils.getStringisEmpty(tally.containerNo),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                        ),
                        Text(
                          Utils.getStringisEmpty(tally.inboundNo),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                        ),
                      ],
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    getContainerNoDetail(tally);
                  },
                  child: Container(
                    margin: EdgeInsets.only(
                      left: 5,
                    ),
                    child: Image.asset(
                      'assets/images/details.png',
                      width: 20,
                      height: 20,
                    ),
                  ),
                ),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  void getContainerNoList() async {
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.getContainerNoList);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      setState(() {
        data = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => Tally.fromJson(userJson)).toList());
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void getContainerNoDetail(Tally tally) async {
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, '${Constants.getContainerNoDetail}/${tally.id}');
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      setState(() {
        List<LPNPhotoDetail> lpnPhotoDetails = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => LPNPhotoDetail.fromJson(userJson)).toList());
        showDialog(
          context: context,
          builder: (context) => LPNPhotoDetailDialog(tally: tally, tallyDetails: lpnPhotoDetails),
        );
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void lpnPhotoCheckContainer(Tally tally) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["warehousingNotifyId"] = tally.id;

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.lpnPhotoCheckContainer, params: map);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      Tally tallyTemp = Tally.fromJson(baseResponse.data);

      LPNPhotoQr lpnPhotoQr1 = new LPNPhotoQr(0, tallyTemp.id, tallyTemp.containerNo, "", "", "", "", "");

      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => LpnPhotoLpnScreen(lpnPhotoQr: lpnPhotoQr1)),
      ).then((value) => {
        if (value != null && value)
          {
            setState(() {
              getContainerNoList();
            })
          }
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void getLpnPhotoInfo(String lpn) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["lpn"] = lpn;

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.getLpnPhotoInfo, params: map);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      LPNPhotoLPN lpnPhotoLPN = LPNPhotoLPN.fromJson(baseResponse.data);
      LPNPhotoQr lpnPhotoQr1 = new LPNPhotoQr(lpnPhotoLPN.id, lpnPhotoLPN.warehousingNotifyId, lpnPhotoLPN.containerNo, lpn, lpnPhotoLPN.photo1, lpnPhotoLPN.photo2, lpnPhotoLPN.photo3, lpnPhotoLPN.photo4);

      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => LpnPhotoSubmit(lpnPhotoQr: lpnPhotoQr1)),
      ).then((value) => {
        if (value != null && value)
          {
            setState(() {
              getContainerNoList();
            })
          }
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    if(Utils.isEmpty(textEditingController.text)){
      ToastContext().init(context);
      Toast.show("scan inbound lpn barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    getLpnPhotoInfo(textEditingController.text);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }
}
